
const MAX_PAGE_WIDTH = 1920;
const MAX_PAGE_HEIGH = 947;
const MIN_PAGE_HEIGH = 30;

class AreaSelection{
  constructor(){
    this.begin = false;
    this.mark = false;
    this.start = {x: 0, y: 0};
    this.end = {x: 0, y: 0};
    this.area = {x0: 0, y0: 0, x1: 0, y1: 0};
    this.style = {top: '0px', left: '0px', width: '0px', height: '0px'};
  }

  selection_start = function (event) {
    let pagex = event.pageX;
    let pagey = event.pageY;
    this.start.x = pagex; //clientX
    this.start.y = pagey; //clientY
    this.end.x = pagex;
    this.end.y = pagey;
    this.begin = true;
  };

  selection = function (event) {
    let pagex = event.pageX;
    let pagey = event.pageY;
    if(pagex > MAX_PAGE_WIDTH){
      pagex = MAX_PAGE_WIDTH
    }
    if(pagey > MAX_PAGE_HEIGH){
      pagey = MAX_PAGE_HEIGH
    }
    if(pagey < MIN_PAGE_HEIGH){
      pagey = MIN_PAGE_HEIGH;
    }
    this.end.x = pagex;
    this.end.y = pagey;
    if(this.begin){
      let deltax = this.end.x - this.start.x;
      let deltay = this.end.y - this.start.y;

      if(deltax !== 0 || deltay !== 0){
        this.mark = true;
      }
    }
    this.style_update();
    return this.area;
  };

  selection_finish = function (event) {
    this.selection(event);
    // let start = this.start;
    // let end = this.end;
    return this.area;
  };


  style_update = function () {
    let start = this.start;
    let end = this.end;
    let deltax = end.x - start.x;
    let deltay = end.y - start.y;
    if(deltax === 0 && deltay === 0){
      return;
    }
    //终点在起点右边
    if(deltax >= 0){
      this.style.left = start.x + 'px';
      this.style.width = deltax + 'px';
      this.area.x0 = start.x;
      this.area.x1 = end.x;
    }else{
      this.style.left = end.x + 'px';
      this.style.width = (start.x - end.x) + 'px';
      this.area.x0 = end.x;
      this.area.x1 = start.x;
    }
    //终点在起点下方
    if(deltay >= 0){
      this.style.top = start.y + 'px';
      this.style.height = deltay + 'px';
      this.area.y0 = start.y;
      this.area.y1 = end.y;
    }else{
      this.style.top = end.y + 'px';
      this.style.height = (start.y - end.y) + 'px';
      this.area.y0 = end.y;
      this.area.y1 = start.y;
    }
  };

  clean = function () {
    this.begin = false;
    this.mark = false;
    this.start = {x: 0, y: 0};
    this.end = {x: 0, y: 0};
    this.style = {top: '0px', left: '0px', width: '0px', height: '0px'}
  }
}

export {AreaSelection}
